<template>
  <div class="top">
    <div class="logo">
      <a href="" @click.prevent="toIndex()">
        <img src="/images/logo.png" />
      </a>
    </div>
    <div class="search">
      <form @submit.prevent="search()">
        <input type="text" v-model="productName" class="s_ipt" />
        <input type="submit" value="搜索" class="s_btn" />
      </form>
      <!-- <span class="fl">
        <a href="#">咖啡</a><a href="#">iphone 6S</a><a href="#">新鲜美食</a>
        <a href="#">蛋糕</a><a href="#">日用品</a><a href="#">连衣裙</a>
      </span> -->
    </div>


    <div class="i_car">
      <div class="car_t">购物车 [ <span>{{ conut }}</span> ]</div>
      <div class="car_bg">
        <!--Begin 购物车未登录 Begin-->
        <div class="un_login" v-if="userId == null">
          还未登录！<a @click.prevent="toLogin()" style="color: #ff4e00">马上登录</a>
          查看购物车！
        </div>
        <!--End 购物车未登录 End-->
        <!--Begin 购物车已登录 Begin-->
        <div v-if="userId != null">
          <ul class="cars">
            <li v-for="(product,index) in productList">
              <a href="#" @click.prevent="toProductDetail(product.id)">
                <div class="img">
                  <img :src="url + product.fileName" width="58" height="58" />
                </div>
                <div class="name">{{ product.name }}</div>
              </a>
              <div class="price"><span style="color:#ff4e00;">￥{{ product.price }}</span>
                 X{{ product.quantity }}
                  <!-- &nbsp;&nbsp;<input type="text" v-model="product.quantity" name="quantity" class="updateQ" @change="updateQuantity(product.quantity,index,product.id)"  -->
                </div>
              <!-- <a href="#" style="height: 10px; width: 30px; "
                @click.prevent="updateProductCount(product.id, product.stock,product.quantity-1)">一</a>
              <a href="#" style="height: 10px; width: 30px; "
                @click.prevent="updateProductCount(product.id, product.stock,product.quantity+1)">十</a> -->
            </li>
          </ul>
          <div v-if="productList.length > 0">
            <div class="price_sum">
              共计&nbsp; <span style="color:#ff4e00;">￥</span><span>{{ cost }}</span>
            </div>
            <div class="price_a"><a href="#" @click.prevent="addOrder()">去购物车结算</a></div>

          </div>
          <div v-else>
            <div class="un_login">购物车为空</div>
          </div>

        </div>
        <!--End 购物车已登录 End-->
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const route = useRoute()
const productName = ref('')

const url = 'http://192.168.12.159:83/';

const conut = ref(0)//总数量
const cost = ref(0)//总价
const userId = sessionStorage.getItem("id");
const loginName = sessionStorage.getItem("loginName");
const productList = ref([])
const numPatten = /^[1-9][0-9]*$/;


const toIndex = () => {
  if (!(route.path === '/')) {
    router.push({ name: 'index' })
  }
}


const search = () => {
  const trimmedName = productName.value.trim()
  router.replace({ name: 'searchProduct', query: { name: trimmedName } })
}

const toLogin = () => {
  router.push({
    name: 'login'
  })
}

const updateQuantity = async (quantity,index,id) => { 
  console.log("quantity:",quantity);
  
    if(!numPatten.test(quantity)){
        productList.value[index].quantity = 1;
        return;
    }
    console.log("数量改动");
    

    updateProductCount(id, productList.value[index].stock,quantity);    
}

//得到购物车的商品
const getProduct = async () => {
  if (userId == null) {
    return;
  }
  try {
    const request = await axios.get("/api/getProductForPayCar", {
      params: {
        userId: userId
      }
    })
    productList.value = request.data.productList;
    cost.value = 0;
    conut.value = 0;
    for (let i = 0; i < productList.value.length; i++) {
      cost.value += productList.value[i].price * productList.value[i].quantity;
      conut.value ++;
    }


  } catch (error) {
    console.error('商品获取失败:', error)
  }

}


//前往订单详情
function goToOrderDetail(orderId) {
  console.log("goToOrderDetail");
  router.push({
    path: '/orderDetailView',
    query: {
      orderId: orderId
    }
  });
}

//购物车页面
const addOrder = async () => {
  
 router.push('/buyCar')
}


// 监听自定义事件
const handleCartUpdate = () => {
  getProduct();
}

// 添加事件监听器
onMounted(() => {
  getProduct();
  window.addEventListener('cart-updated', handleCartUpdate);
})

// 移除事件监听器
onUnmounted(() => {
  window.removeEventListener('cart-updated', handleCartUpdate);
})


//查看详情
function toProductDetail(id) {
  router.push({
    path: '/productDetail',
    query: {
      id: id
    }
  })
}





</script>

<style>
.updateQ{
	width:30px; height:13px;  background:none; color:#555555; font-size:15px; text-align:center; font-family:"Microsoft YaHei";  border: black solid 1px ;
}
</style>